using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AbstractGameEntry : MonoBehaviour
{
    private readonly Dictionary<Type, Dictionary<string, object>> _registeredClasses =
       new Dictionary<Type, Dictionary<string, object>>();
    public void RegisterSystem<T>(T instance, string key = null) where T : class
    {
        Type type = typeof(T);
        string instanceKey = key ?? type.Name;

        if (!_registeredClasses.ContainsKey(type))
        {
            _registeredClasses[type] = new Dictionary<string, object>();
        }

        if (_registeredClasses[type].ContainsKey(instanceKey))
        {
            Debug.LogWarning($"已存在类型 {type.Name} 的实例，键为 {instanceKey}，将被覆盖");
        }

        _registeredClasses[type][instanceKey] = instance;
        Debug.Log($"已注册类型 {type.Name} 的实例，键为 {instanceKey}");
    }
    /// <summary>
    /// 取消注册一个类实例
    /// </summary>
    public void UnregisterSystem<T>(string key = null) where T : class
    {
        Type type = typeof(T);
        string instanceKey = key ?? type.Name;

        if (_registeredClasses.TryGetValue(type, out var instances))
        {
            if (instances.Remove(instanceKey))
            {
                Debug.Log($"已取消注册类型 {type.Name} 的实例，键为 {instanceKey}");
            }
            else
            {
                Debug.LogWarning($"未找到类型 {type.Name} 的实例，键为 {instanceKey}");
            }

            if (instances.Count == 0)
            {
                _registeredClasses.Remove(type);
            }
        }
    }

    /// <summary>
    /// 获取已注册的类实例
    /// </summary>
    public T GetSystem<T>(string key = null) where T : class
    {
        Type type = typeof(T);
        string instanceKey = key ?? type.Name;

        if (_registeredClasses.TryGetValue(type, out var instances))
        {
            if (instances.TryGetValue(instanceKey, out var instance))
            {
                return (T)instance;
            }
        }

        Debug.LogWarning($"未找到类型 {type.Name} 的实例，键为 {instanceKey}");
        return null;
    }

    /// <summary>
    /// 检查是否存在指定类型的实例
    /// </summary>
    public bool Has<T>(string key = null) where T : class
    {
        Type type = typeof(T);
        string instanceKey = key ?? type.Name;

        return _registeredClasses.TryGetValue(type, out var instances) &&
               instances.ContainsKey(instanceKey);
    }

    /// <summary>
    /// 清除所有注册的类实例
    /// </summary>
    public void ClearAll()
    {
        _registeredClasses.Clear();
        Debug.Log("已清除所有注册的类实例");
    }
}
